package it.fuesi.bubblekids.activities;

import it.fuesi.bubblekids.R;
import it.fuesi.bubblekids.model.BubbleConfig;
import it.fuesi.bubblekids.model.PreferenceName;
import it.fuesi.bubblekids.utils.FormatUtils;
import it.fuesi.bubblekids.views.CircleArea;
import it.fuesi.bubblekids.views.CirclesDrawingView;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.Random;



public class MainActivity extends Activity {

    private CirclesDrawingView mCircleView;
    private TextView mHighestScore;
    private ImageView mSettings;
    private LinearLayout mPlayLayout;
    private TextView mScore;
    private TextView mTime;
    private long start;
    private long end;

    private FrameLayout mDecorView;

    private static final int N_CIRCLES = 10;

    private static final String TAG = "MainActivity";

    private static BubbleConfig config = new BubbleConfig();

    public static BubbleConfig getConfig(){
        return config;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "On Activity result --> requestCode:" + requestCode + " - resultCode:" + resultCode);

        if(requestCode == SettingsActivity.REQUEST_CODE){
            if(resultCode == RESULT_OK){
                loadConfig();
                mCircleView.init(this);
            }
        }
    }

    private void loadConfig(){
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        config = new BubbleConfig();
        config.setN_bubbles(prefs.getInt(PreferenceName.n_circles.toString(), 10));
        config.setMax_radius(prefs.getInt(PreferenceName.max_circle_radius.toString(), 150));
        config.setMin_radius(prefs.getInt(PreferenceName.min_circle_radius.toString(), 30));
        config.setBgColor(prefs.getString(PreferenceName.bg_color.toString(), "0-0-0"));
        config.setHighest_score(prefs.getInt(PreferenceName.highest_score.toString(), 0));
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadConfig();

        setContentView(R.layout.activity_main);

        mDecorView = (FrameLayout)findViewById(R.id.main_layout);

        mPlayLayout = (LinearLayout)findViewById(R.id.play_layout);

        mCircleView = (CirclesDrawingView)findViewById(R.id.circle_view);

        mCircleView.setCirclesDestroyedEventListener(new CirclesDrawingView.OnCirclesDestroyed() {
            @Override
            public void onEvent() {
                stop();
            }
        });

        mCircleView.setOnScoreUpdatedEventListener(new CirclesDrawingView.OnScoreUpdated(){
            @Override
            public void onEvent(int newScore) {
                updateScore(newScore);
            }
        });



        mPlayLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                play();
            }
        });


        mSettings = (ImageView)findViewById(R.id.configure);
        mSettings.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                showSettings();
            }
        });

        mScore = (TextView)findViewById(R.id.score);
        mHighestScore = (TextView)findViewById(R.id.highest_score);
        mHighestScore.setText(""+config.getHighest_score());
        mTime = (TextView)findViewById(R.id.time);


    }

    @Override
    protected void onStart() {
        super.onStart();

        hideSystemUI();
    }

    // This snippet hides the system bars.
    private void hideSystemUI() {
        // Set the IMMERSIVE flag.
        // Set the content to appear under the system bars so that the content
        // doesn't resize when the system bars hide and show.
        mDecorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

    // This snippet shows the system bars. It does this by removing all the flags
// except for the ones that make the content appear under the system bars.
    private void showSystemUI() {
        mDecorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }


    private void updateScore(int newScore){
        mScore.setText(""+newScore);
    }

    public void play(){
        start = System.currentTimeMillis();
        addCircles();
        mPlayLayout.setVisibility(View.GONE);
        mSettings.setVisibility(View.GONE);
        mCircleView.setPlay(true);
    }

    public void stop(){
        end = System.currentTimeMillis();
        mPlayLayout.setVisibility(View.VISIBLE);
        mSettings.setVisibility(View.VISIBLE);
        mCircleView.setPlay(false);
        calculateScore();
    }

    private void calculateScore(){
        long currentTime = end-start;
        mTime.setText(FormatUtils.formatTime(currentTime));
        int currentScore = mCircleView.getScore();

        int currentTimeS = (int)currentTime / 1000;

        if(currentTimeS < 60)
            currentScore += (60-currentTimeS);

        updateScore(currentScore);
        if(currentScore > config.getHighest_score()){
            updateHighestScore(currentScore);
        }
    }

    private void updateHighestScore(int currentScore){
        config.setHighest_score(currentScore);
        mHighestScore.setText(""+currentScore);
        mHighestScore.setTextColor(getResources().getColor(android.R.color.holo_red_light));
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putInt(PreferenceName.highest_score.toString(), currentScore).commit();

    }



    private void showSettings(){
        Intent i = new Intent(this, SettingsActivity.class);
        startActivityForResult(i, SettingsActivity.REQUEST_CODE);
    }



    private void addCircles() {
        int bottom = mCircleView.getBottomValue();
        int top = mCircleView.getTopValue();
        int left = mCircleView.getLeftValue();
        int right = mCircleView.getRightValue();

        Log.d(TAG, "Start playing --> config: " + config.toString());

        for(int i=0; i<config.getN_bubbles(); i++){

            mCircleView.addCircle(new CircleArea(FormatUtils.randInt(left, right), FormatUtils.randInt(top, bottom), FormatUtils.randInt(config.getMin_radius(), config.getMax_radius())));

        }
    }







}
